import uuid as uuid_pkg
import pytz
from enum import Enum
from datetime import datetime
from typing import Optional, Dict, Any
from sqlalchemy import String, DateTime, Integer, Enum as SQLAlchemyEnum
from sqlalchemy.orm import Mapped, mapped_column
from app.core.db.database import Base
from app.core.config import config


class OrderStatus(Enum):
    """ 订单状态 """

    # 待支付
    WAITING_PAY = "waiting_pay"
    # 失败
    FAILED = "failed"
    # 已支付
    PAID = "paid"
    # 已退款
    REFUNDED = "refunded"
    # 已取消
    CANCELLED = "cancelled"
    
    def __str__(self):
        return self.value


time_zone = pytz.timezone(config.get("timezone", default='Asia/Shanghai'))


class Order(Base):
    """ 订单信息 """
    __tablename__ = "orders"

    id: Mapped[int] = mapped_column("id", autoincrement=True, nullable=False, unique=True, primary_key=True, init=False, comment='主键id')
    payload_id: Mapped[str] = mapped_column(String(255), nullable=True, default='', comment='用户标识')
    order_trade_no: Mapped[str] = mapped_column(String(255), nullable=True, default='', comment='订单交易号', unique=True)
    order_amount: Mapped[int] = mapped_column(String(255), nullable=False, default=None, comment='订单金额')
    order_status: Mapped[OrderStatus] = mapped_column(SQLAlchemyEnum(OrderStatus, native_enum=False), nullable=True, default=OrderStatus.WAITING_PAY, comment='订单支付状态')
    order_time: Mapped[datetime] = mapped_column(DateTime(timezone=True), default_factory=lambda: datetime.now(time_zone), comment='订单时间')
    description: Mapped[str] = mapped_column(String(255), nullable=True, default='', comment='订单描述')
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default_factory=lambda: datetime.now(time_zone), comment='创建时间')
    updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), default=None, comment='更新时间')
    is_deleted: Mapped[bool] = mapped_column(default=False, index=True, comment='是否删除')
    
    def __str__(self):
        return f"Order(trade_no={self.order_trade_no}, status={self.order_status})"
